import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:yw_bapp/dao/withdrawal_dao.dart';
import 'package:yw_bapp/model/applay_withdrawal_model.dart';
import 'package:yw_bapp/pages/select_bank_page.dart';
import 'package:yw_bapp/pages/withdrawal_list.dart';
import 'package:yw_bapp/provider/store_info_provider.dart';
import 'package:yw_bapp/utils/precision_limit_formatter.dart';
import 'package:yw_bapp/widgets/custom_route_widget.dart';
import 'package:yw_bapp/widgets/loading_pop_widget.dart';
import 'package:yw_bapp/widgets/m_btn.dart';
import 'package:yw_bapp/widgets/optional_widget.dart';
import 'package:yw_bapp/widgets/safe_area_bar_widget.dart';
import 'package:yw_bapp/widgets/show_toast.dart';
import 'package:yw_bapp/widgets/text_image_widget.dart';
import 'package:provider/provider.dart';
import 'package:yw_bapp/widgets/wrap_gesture_widget.dart';

class GoCashPage extends StatefulWidget {
  @override
  _GoCashPageState createState() => _GoCashPageState();
}

class _GoCashPageState extends State<GoCashPage> {
  TextStyle actionStyle =
      TextStyle(color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold);
  final titleStyle =
      TextStyle(color: ColorUtil.color('#FF999999'), fontSize: 11);
  // 输入框控制器
  TextEditingController moneyController = TextEditingController();
  // 下一步按钮的颜色
  bool isActive = false;
  // 按钮点击色
  Color btnActiveColor = ColorUtil.color('#FFC49226');
  // 按钮默认色
  Color btnDefaultColor = ColorUtil.color('#FFCCCCCC');
  // 文字点击色
  Color textActiveColor = Colors.white;
  // 文字默认色
  Color textDefaultColor = Colors.white;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadData(context);
  }

  @override
  Widget build(BuildContext context) {
    final int balance = context.watch<StoreInfoProvider>().balance ?? 0;
    // 门店的银行卡账户
    String bankName =
        context.watch<StoreInfoProvider>().storeInfo?.bankName ?? '去设置';
    // 承兑汇率
    dynamic rate =
        context.watch<StoreInfoProvider>().storeInfo?.scoreRatio ?? 10000;
    // 手续费率
    dynamic serviceRate =
        context.watch<StoreInfoProvider>().storeInfo?.withdrawRatio ?? 0;
    // 实际到账金额
    num finallMoney = 0;
    // 手续费金额
    num serviceMoney = 0;
    // 开心豆承兑人民币的价值
    num rmbPrice = 0;
    return Scaffold(
        appBar: XAppBar(
          statusBarColor: ColorUtil.color('#FFC49226'),
          bgColor: ColorUtil.color('#FFC49226'),
          title: "去兑现",
          fun: () {},
        ),
        body: Container(
          color: Color.fromRGBO(233, 233, 233, 1),
          padding: EdgeInsets.only(top: 10),
          child: Column(
            children: [
              OptionalWidget(
                leadingText: '兑现账户',
                callBack: () => _toNextPage(context),
                actionText: "$bankName",
                actionStyle: bankName != '去设置' ? actionStyle : TextStyle(),
                iconShow: bankName != '去设置' ? false : true,
              ),
              Container(
                color: Colors.white,
                margin: EdgeInsets.only(top: 10, bottom: 54),
                padding: EdgeInsets.fromLTRB(15, 17, 15, 17),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text("兑现金额"),
                    // 副标题
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        TextWithImage(
                          title: '单次兑现不得小于100',
                          imageUrl: 'images/bean.png',
                          textStyle: titleStyle,
                          func: () {},
                        )
                      ],
                    ),
                    // 输入框
                    TextField(
                        controller: moneyController,
                        keyboardType:
                            TextInputType.numberWithOptions(decimal: true),
                        maxLength: 11,
                        autofocus: false,
                        inputFormatters: [PrecisionLimitFormatter(2)],
                        decoration: InputDecoration(
                            hintText: "请输入兑现金额",
                            helperStyle: TextStyle(
                              color: Colors.transparent,
                            ),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.grey)),
                            hintStyle: TextStyle(
                                color: ColorUtil.color("#FF999999"),
                                fontWeight: FontWeight.normal,
                                fontSize: 15)),
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 40),
                        onChanged: (String value) {
                          if (int.parse(value) >= 100) {
                            setState(() {
                              isActive = true;
                            });
                          } else {
                            setState(() {
                              isActive = false;
                            });
                          }
                        }),
                    //
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TextWithImage(
                          title: '可兑现：${balance / 100}',
                          imageUrl: 'images/bean.png',
                          textStyle: titleStyle,
                          func: () {},
                        ),
                        wrapGesture(
                            child: Text("全部兑现",
                                style: TextStyle(
                                    color: ColorUtil.color("#FFC49226"),
                                    fontSize: 13)),
                            function: () => _totalCharge(context, balance)),
                      ],
                    )
                  ],
                ),
              ),
              MBtn(
                btnWidth: 325,
                btnHeight: 47,
                borderRadius: 5,
                title: '确认兑现',
                hasBg: true,
                textColor: isActive ? textActiveColor : textDefaultColor,
                bgColor: isActive ? btnActiveColor : btnDefaultColor,
                borderColor: isActive ? btnActiveColor : btnDefaultColor,
                function: () => _rechargePop(context, finallMoney, rate,
                    serviceMoney, balance, serviceRate, rmbPrice),
              )
            ],
          ),
        ));
  }

  // 数据加载
  void _loadData(BuildContext context) async {
    // 获取账户余额
    await Future.delayed(Duration(seconds: 2), () {
      // 获取账户
      LoadingPop.hide(context);
    });
  }

  _toNextPage(BuildContext context) {
    Navigator.of(context).push(CustomRoute(SelectBankPage(), 5));
  }

  // 点击就全部的余额填写到输入框
  _totalCharge(BuildContext context, int balance) {
    moneyController.text = '${balance / 100}';
  }

// 提交兑现申请
  _toApplayWithdraw(BuildContext context, scorenum, rmbPrice, payPrice,
      servicePrice, scoreRatio, withdrawRatio) {
    LoadingPop.show(context);
    print(rmbPrice.runtimeType);
    WithdrawalDao.ApplayWithdrawal(scorenum, rmbPrice, payPrice, servicePrice,
            scoreRatio, withdrawRatio)
        .then((ApplayWithdrawalModel model) => {
              LoadingPop.hide(context),
              if (model.status == 200)
                {
                  ShowToast.toast(context,
                      msg: "申请提交成功", position: ToastPostion.center),
                  moneyController.text = '',
                  Navigator.of(context).push(CustomRoute(WithdrawalList(), 5)),
                  LoadingPop.show(context)
                }
            });
  }

  // 兑现的确认弹窗
  _rechargePop(
      BuildContext context,
      dynamic finallMoney,
      dynamic rate,
      dynamic serviceMoney,
      dynamic balance,
      dynamic serviceRate,
      dynamic rmbPrice) {
    final titleStyle =
        TextStyle(color: ColorUtil.color("#FF666666"), fontSize: 13);
    final cashMoney = num.parse(moneyController.text)*100;
    // 实际到账金额
    finallMoney = double.parse(rate) / 10000 * cashMoney * (1 - double.parse(serviceRate)/ 10000) / 100;
    // 承兑X输入
    rmbPrice =  double.parse(rate) / 10000 * cashMoney / 100;
    // 手续费
    serviceMoney = rmbPrice * ( double.parse(serviceRate)  / 10000);
    // 手续费类型转换
    serviceMoney = serviceMoney.toStringAsFixed(2);
    if (cashMoney / 100 < 100) {
      ShowToast.toast(context,
          msg: "单次兑现不得小于100", position: ToastPostion.center);
      return;
    }
    if (cashMoney / 100 > balance) {
      ShowToast.toast(context, msg: "超出账户可兑现余额", position: ToastPostion.center);
      return;
    }
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            width: 375,
            height: 384,
            padding: EdgeInsets.fromLTRB(18, 21, 18, 21),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 标题
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    IconButton(
                      icon: Icon(Icons.close),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 100),
                      child: Text(
                        "到账确认",
                        style: TextStyle(color: Colors.black, fontSize: 18),
                      ),
                    )
                  ],
                ),
                // 实际到账金额
                Container(
                  child: DefaultTextStyle(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("￥"),
                        Text(
                          "$finallMoney",
                          style: TextStyle(
                              fontSize: 40, fontWeight: FontWeight.bold),
                        )
                      ],
                    ),
                    style: TextStyle(fontSize: 18, color: Colors.black),
                  ),
                ),
                TextWithImage(
                  title: '实际到账金额',
                  imageUrl: 'images/question_orange.png',
                  textStyle: titleStyle,
                  imgWdth: 16,
                  imgHeight: 16,
                  func: () {},
                ),
                // 线
                Container(
                  margin: EdgeInsets.only(top: 29),
                  color: ColorUtil.color("#1A000000"),
                  height: 1,
                ),
                // 兑现的明细
                Column(
                  children: [
                    cashItems("兑现开心豆数量", '${cashMoney/100}'),
                    cashItems("承兑汇率", '${double.parse(rate) / 100}%'),
                    cashItems("手续费", '$serviceMoney'),
                  ],
                ),
                // 按钮
                MBtn(
                  btnWidth: 340,
                  btnHeight: 44,
                  borderColor: ColorUtil.color("#FFC49226"),
                  bgColor: ColorUtil.color("#FFC49226"),
                  hasBg: true,
                  borderRadius: 5,
                  function: () => _toApplayWithdraw(context, cashMoney/100,
                      rmbPrice, finallMoney, serviceMoney, rate, serviceRate),
                  title: '确认兑现',
                )
              ],
            ),
          );
        });
  }

  Widget cashItems(String s, dynamic i) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      child: DefaultTextStyle(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("$s"),
            Text(
              "$i",
              style: TextStyle(color: Colors.black),
            )
          ],
        ),
        style: TextStyle(color: ColorUtil.color("#FF666666"), fontSize: 13),
      ),
    );
  }
}
